package org.vectrics.site.hosted;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.vectrics.client.webclient.HttpRequester;
import org.vectrics.client.webclient.ServerCommand;
import org.vectrics.client.webclient.ServerConfig;
import org.vectrics.client.webclient.ServiceConnection;
import org.vectrics.common.util.DateUtil;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.PasswordEncryptor;


public class EstablishHostedAction extends VectricsStrutsAction {
	private transient Logger log = Logger.getLogger(this.getClass());
	
	public EstablishHostedAction() {
		super();
	}
	
	protected String doExecute(VectricsActionData actionData)	throws JspException {
		log.info("doExecute() - starting");
		HostedApplicationForm form = (HostedApplicationForm)actionData.getForm();
		
		String code = actionData.getRequest().getParameter("code");
		String applicationId = actionData.getRequest().getParameter("applicationId");
		HostedApplication application = (HostedApplication)ThreadProperties.getSession().load(HostedApplication.class, new Long(applicationId));
		String password = application.getPerson().getUser().getPassword();
		String encryptedPassword = null;
		if (application.getPerson().getUser().getPasswordEncrypted()) {
			encryptedPassword = password;
		} else {
			PasswordEncryptor encryptor = new PasswordEncryptor();
			encryptedPassword = encryptor.crypt(password);
		}
		String forward = "success";
		if (code.equals(encryptedPassword)) {
			HttpRequester httpRequester = new HttpRequester();
			ServerConfig serverConfig = new ServerConfig();
			//serverConfig.setIpAddress("www.vectrics.com");
			serverConfig.setIpAddress("localhost");
			serverConfig.setLocation("/hrs-intranet/ws");
			serverConfig.setPort("80");
			ServiceConnection serviceConnection = new ServiceConnection();
			serviceConnection.setAuthExpiration(DateUtil.addMinutesToToday(10));
			serviceConnection.setConfig(serverConfig);
			serviceConnection.setUserName("admin");
			serviceConnection.setPassword("vectrics");
			serviceConnection.setDomainId("1");
			ServerCommand serverCommand = new EstablishSiteCommandRemote(application);
			httpRequester.execute(serviceConnection, serverCommand);
			forward = "success";
		} else {
			forward = "bad.code";
		}
		
		
		
		
		return(forward);
	}
	
}
